package com.SouthernWall_404.Age_Capitalism.common.Network.C2S;

import com.SouthernWall_404.Age_Capitalism.common.Gui.Menu.ModMerchantMenu;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.PacketListener;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.PacketUtils;
import net.minecraft.network.protocol.game.ServerGamePacketListener;
import net.minecraft.network.protocol.game.ServerboundSelectTradePacket;
import net.minecraft.server.RunningOnDifferentThreadException;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.thread.BlockableEventLoop;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MerchantMenu;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public class MerchantClientPacket {

    private final int item;
    private ServerPlayer player;

    public MerchantClientPacket(int p_134462_) {
        this.item = p_134462_;
    }

    public MerchantClientPacket(FriendlyByteBuf p_179747_) {
        this.item = p_179747_.readVarInt();
    }

    public void encode(FriendlyByteBuf p_134471_) {
        p_134471_.writeVarInt(this.item);
    }

    public boolean handle(Supplier<NetworkEvent.Context> supplier)
    {
        var content=supplier.get();
        content.enqueueWork(() -> {

            handleSelectTrade(this,supplier);

        });


        content.setPacketHandled(true);
        return true;
    }

    public int getItem() {
        return this.item;
    }


    public void handleSelectTrade(MerchantClientPacket msg,Supplier<NetworkEvent.Context> supplier) {

        player=supplier.get().getSender();
//        ensureRunningOnSameThread(msg, this, this.player.serverLevel());
        int i = msg.getItem();
        AbstractContainerMenu abstractcontainermenu = this.player.containerMenu;
        if (abstractcontainermenu instanceof ModMerchantMenu modMerchantMenu) {
            if (!modMerchantMenu.stillValid(this.player)) {

//                LOGGER.debug("Player {} interacted with invalid menu {}", this.player, merchantmenu);
                return;
            }

            modMerchantMenu.setSelectionHint(i);
            modMerchantMenu.tryMoveItems(i);
        }

    }

}


